package org.cunamas.web.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.cunamas.core.bean.BudgetInputBean;
import org.cunamas.core.bean.LogBean;
import org.cunamas.core.dto.Filtros;
import org.cunamas.core.service.ExcelReportService;
import org.cunamas.core.service.ReportesCunamasService;
import org.cunamas.web.util.CunamasConstants;
import org.cunamas.web.util.MessagesView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BudgetReportController {
	
	@Autowired
	private ExcelReportService excelReportService;
	
	@Autowired
	private ReportesCunamasService cunamasService;
    
    private boolean flagLoaded;
    private String messageError;
    private boolean validForm;
    private Long anio;
    private Long mes;
    
    private String fileName = null;
    private String nameFile = null;

	public void loadDefaultValues(){
		messageError = null;
    	anio = null;
    	mes = null;
    	fileName = null;
    	nameFile = null;
    }
	
	public String downloadFile(){
		HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
		response.setContentType("application/force-download");
		
		response.addHeader("Content-Disposition", "attachment; filename=\"" + nameFile + ".xls\"");
		byte[] buf = new byte[1024];
		
		try{
		  File file = new File(fileName);
		  long length = file.length();
		  BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
		  ServletOutputStream out = response.getOutputStream();
		  response.setContentLength((int)length);
		  while ((in != null) && ((length = in.read(buf)) != -1)) {
		    out.write(buf, 0, (int)length);
		  }
		  in.close();
		  out.flush();
		  out.close();
		}
		catch (Exception exc){
		  exc.printStackTrace();
		}
		
		FacesContext.getCurrentInstance().responseComplete();
		return null;
	}
	
	public void buildBudgetReport(){
		if(!validForm) return;
		LogBean logBean=null;
		
		
		try{
			List<BudgetInputBean> budgetInputBeans = excelReportService.processBudgetReport(anio, mes);
			
			if(budgetInputBeans==null || budgetInputBeans.size()==0){
				messageError = MessagesView.getI18nMessage("budgetReport.inputData.null");
				return;
			}
			
			String fileTemplateName = CunamasConstants.DATA_LOAD_TEMPLATE_ROUTE + CunamasConstants.BUDGET_REPORT_NAME + ".xls";
			
			nameFile = CunamasConstants.BUDGET_REPORT_NAME + 
					"_" + anio + "_" + mes; 
			
			fileName = CunamasConstants.DATA_LOAD_OUTPUT_ROUTE + nameFile + "_" + System.currentTimeMillis() + ".xls";
			
			excelReportService.fileCopyFromTemplate(fileTemplateName, fileName);
			
			excelReportService.buildExcelReport(fileName, budgetInputBeans);
			
			logBean = new LogBean(CunamasConstants.COD_REPORTE_PRESUPUESTAL, CunamasConstants.NOMBRE_REPORTE_PRESUPUESTAL, fileName, new Date(), new Short("1"),"");

		}catch(Exception e){
			e.printStackTrace();
			messageError = e.getMessage();
			fileName = null;
			logBean = new LogBean(CunamasConstants.COD_REPORTE_PRESUPUESTAL, CunamasConstants.NOMBRE_REPORTE_PRESUPUESTAL, fileName, new Date(), new Short("0"),e.getMessage());
		}
		
		cunamasService.persistLog(logBean);
	}
	
    public void validate(){
    	validForm = true;
    	messageError = null;
    	
    	if(anio==null || anio.equals(0L)){
    		messageError = MessagesView.getI18nMessage("general.anio.null");
    		validForm = false;
    		return;
    	}
    	
    	if(mes==null || mes.equals(0L)){
    		messageError = MessagesView.getI18nMessage("general.mes.null");
    		validForm = false;
    		return;
    	}
    }

	public boolean isFlagLoaded() {
		return flagLoaded;
	}

	public void setFlagLoaded(boolean flagLoaded) {
		this.flagLoaded = flagLoaded;
	}

	public Long getAnio() {
		return anio;
	}

	public void setAnio(Long anio) {
		this.anio = anio;
	}

	public Long getMes() {
		return mes;
	}

	public void setMes(Long mes) {
		this.mes = mes;
	}

	public String getMessageError() {
		return messageError;
	}

	public void setMessageError(String messageError) {
		this.messageError = messageError;
	}



	public boolean isValidForm() {
		return validForm;
	}



	public void setValidForm(boolean validForm) {
		this.validForm = validForm;
	}



	public String getFileName() {
		return fileName;
	}



	public void setFileName(String fileName) {
		this.fileName = fileName;
	}


	public String getNameFile() {
		return nameFile;
	}

	public void setNameFile(String nameFile) {
		this.nameFile = nameFile;
	}
    

    
}